package com.tsd.jxc.config;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.tsd.core.cache.CacheConstants;
import com.tsd.core.cache.CacheOperatorApi;
import com.tsd.core.cache.utils.CreateRedisTemplateUtils;
import com.tsd.jxc.setting.cache.JxcSettingCache;
import com.tsd.jxc.setting.cache.JxcSettingRedisCache;
import com.tsd.jxc.vo.JxcSettingVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

/**
 * @ClassName: JxcCacheConfig
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2022/11/18 15:54
 * @Version: 1.0
 */
@Configuration
@PropertySource(value = {"classpath:redis.properties"}, ignoreResourceNotFound = true)
public class JxcCacheConfig {

    @Value("${redis.config.enable}")
    private boolean enable = false;

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 进销存系统配置缓存
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "jxcSettingCacheOperatorApi")
    public CacheOperatorApi<JxcSettingVo> jxcSettingCacheOperatorApi() {
        if (enable) {
            RedisTemplate<String, JxcSettingVo> redisTemplate = CreateRedisTemplateUtils.createObject(redisConnectionFactory);
            return new JxcSettingRedisCache(redisTemplate);
        }
        TimedCache<String, JxcSettingVo> timedCache = CacheUtil.newTimedCache(CacheConstants.DEFAULT_CACHE_TIMEOUT_HOUR);
        return new JxcSettingCache(timedCache);
    }
}
